﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using InductBase;

namespace InductBase.Helpers
{
    class BasicTypesConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(Rec)) return true;
            if (destinationType == typeof(Vec2)) return true;
            if (destinationType == typeof(Vec2i)) return true;
            if (destinationType == typeof(Transformation)) return true;
            if (context != null && destinationType == typeof(string))
            {
                return true;
            }

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            Type type = value.GetType();
            if (context != null && type == typeof(string))
            {
                if (context.PropertyDescriptor.PropertyType == typeof(Rec)) return Rec.Parse(value.ToString());
                if (context.PropertyDescriptor.PropertyType == typeof(Vec2)) return Vec2.Parse(value.ToString());
                if (context.PropertyDescriptor.PropertyType == typeof(Vec2i)) return Vec2i.Parse(value.ToString());
                if (context.PropertyDescriptor.PropertyType == typeof(Transformation)) return Transformation.Parse(value.ToString());
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {

            if (destinationType == typeof(Rec)) return Rec.Parse(value.ToString());
            if (destinationType == typeof(Vec2)) return Vec2.Parse(value.ToString());
            if (destinationType == typeof(Vec2i)) return Vec2i.Parse(value.ToString());
            if (destinationType == typeof(Transformation)) return Transformation.Parse(value.ToString());
            if (destinationType == typeof(String)) return value != null ? value.ToString() : String.Empty;

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
